package com.whf.android.jar.media;

import android.content.ContentResolver;
import android.content.Intent;
import android.database.ContentObserver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.CallLog;
import android.provider.MediaStore;
import android.provider.Settings;
import android.text.TextUtils;

import com.whf.android.jar.app.Latte;
import com.whf.android.jar.util.file.FilePathUtils;
import com.whf.android.jar.util.file.SdkVersionUtils;
import com.whf.android.jar.util.log.LatteLogger;


/**
 * 多媒体内容观察者（观察媒体数据库的改变）
 *
 * @author qf
 * @version 1.0.3
 */
final class MediaContentObserver extends ContentObserver {

    private static final String[] MEDIA_PROJECTIONS = {
            MediaStore.Images.ImageColumns.DATA,
            MediaStore.Images.ImageColumns.WIDTH,
            MediaStore.Images.ImageColumns.HEIGHT
    };

    /**
     * 截图关键字。
     */
    private static final String[] KEYWORDS = {
            "screenshots", "screen_shots", "screen-shots", "screen shots",
            "screenshot", "screen_shot", "screen-shot", "screen shot",
            "screen_capture", "screen_capture", "screen-capture", "screen capture",
            "screen_cap", "screen_cap", "screen-cap", "screen cap",
            "截屏"
    };

    private final Uri mContentUri;

    private final ContentResolver mContentResolver;
    private final IScreenshotCallBack mScreenshotCallBack;


    /**
     * Creates a content observer.
     *
     * @param handler The handler to run {@link #onChange} on, or null if none.
     */
    public MediaContentObserver(Uri contentUri, Handler handler,
                                ContentResolver contentResolver,
                                IScreenshotCallBack callBack) {
        super(handler);
        mContentUri = contentUri;
        mContentResolver = contentResolver;
        mScreenshotCallBack = callBack;
        LatteLogger.i("contentUri:" + contentUri);
    }

    @Override
    public void onChange(boolean selfChange) {
        super.onChange(selfChange);
        LatteLogger.i("图片数据改变了");
        handleMediaContentChange(mContentUri);
    }

    /**
     * 数据改变时查询数据库中最后加入的一条数据，处理获取到的第一行数据。
     */
    private void handleMediaContentChange(Uri contentUri) {
        Cursor cursor = null;
        try {
            if (TextUtils.isEmpty(contentUri.getAuthority())) {
                LatteLogger.i("个别小米手机返回数据");
                if (mScreenshotCallBack != null) {
                    mScreenshotCallBack.screenshotTaken(contentUri.getPath());
                }
                return;
            }
            if (SdkVersionUtils.isR()) {
                if (!Environment.isExternalStorageManager()) {
                    //R以上的特殊存储权限
                    Intent intent = new Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION);
                    intent.setData(Uri.parse("package:" + Latte.getApplicationContext().getPackageName()));
                    Latte.getActivity().startActivityForResult(intent, 1255);
                    return;
                }
                // limit 条件
                Uri limitedCallLogUri = CallLog.Calls.CONTENT_URI.buildUpon()
                        .appendQueryParameter(CallLog.Calls.LIMIT_PARAM_KEY, "1")
                        .build();

                Bundle queryArgs = new Bundle();
                queryArgs.putInt(ContentResolver.QUERY_ARG_OFFSET, 0);
                queryArgs.putInt(ContentResolver.QUERY_ARG_LIMIT, limitedCallLogUri.getPort());

                cursor = mContentResolver.query(contentUri, MEDIA_PROJECTIONS,
                        queryArgs, null);
            } else {
                cursor = mContentResolver.query(contentUri, MEDIA_PROJECTIONS,
                        null, null,
                        MediaStore.Images.ImageColumns.DATE_ADDED + " desc limit 1"
                );
            }
            if (cursor == null) {
                return;
            }
            if (!cursor.moveToFirst()) {
                return;
            }
            //获取各列的索引
            int dataIndex = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
            //获取行数据
            String data = cursor.getString(dataIndex);
            //处理第一条 数据
            handleMediaRowData(data);
        } catch (Exception ex) {
            ex.printStackTrace();
            LatteLogger.e(ex.getMessage());
        } finally {
            if (cursor != null && !cursor.isClosed()) {
                cursor.close();
            }
        }
    }

    /**
     * 处理监听到的资源，设置最大等待时间500ms （因为某些魅族手机保存有延迟）
     *
     * @param path:
     */
    private void handleMediaRowData(final String path) {
        long duration = 0;
        long step = 100;
        while (!checkScreenShot(path) && duration <= 500) {
            LatteLogger.i("duration:" + duration);
            try {
                duration += step;
                Thread.sleep(step);
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
        String cameraPath = FilePathUtils.cameraPath(path);
        if (checkScreenShot(cameraPath)) {
            if (mScreenshotCallBack != null) {
                mScreenshotCallBack.screenshotTaken(cameraPath);
            }
        } else {
            LatteLogger.e("screenshot is null,不是截图的图片");
        }
    }

    /**
     * 判断是否是截屏
     *
     * @param path:
     */
    private boolean checkScreenShot(String path) {
        if (path == null) {
            LatteLogger.e("null path");
            return false;
        }
        path = path.toLowerCase();
        //
        LatteLogger.i("截屏，path：" + path);
        for (String keyWork : KEYWORDS) {
            if (path.contains(keyWork)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 截屏监听工具
     */
    public interface IScreenshotCallBack {
        void screenshotTaken(String path);
    }
}
